﻿
using Seven.ERP.EntityFarmworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Seven.ERP.Repositories
{
    public class BaseRepository<T>:IBaseRepository<T> where T : class
    {
        /// <summary>
        /// 注入上下文
        /// </summary>
        private readonly ERPDbContext db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public BaseRepository(ERPDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public int Add(T entity)
        {
            db.Set<T>().Add(entity);
            return db.SaveChanges();
        }
        /// <summary>
        /// 删除(真删)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Delete(T entity)
        {
            db.Set<T>().Remove(entity);
            return db.SaveChanges();
        }
        /// <summary>
        /// 获取全部
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll2()
        {
           return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public int Update(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChanges();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public int UpdateRange(List<T> entities)
        {
            db.Set<T>().UpdateRange(entities);
            return db.SaveChanges();
        }
        /// <summary>
        /// 返回单个对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetSingle(int id)
        {
            return db.Set<T>().Find(id);
        }
    }
}
